package main

import (
	"log"

	"xadmin/backend/config"
	"xadmin/backend/internal/api"
	"xadmin/backend/internal/middleware"
	"xadmin/backend/internal/repository"
	"xadmin/backend/internal/service"
	"xadmin/backend/pkg/database"
	"xadmin/backend/pkg/logger"

	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"

	_ "xadmin/backend/docs" // 这里导入生成的 docs
)

// @title XAdmin API
// @version 1.0
// @description This is the API for XAdmin backend.
// @host localhost:8080
// @BasePath /api/v1
func main() {
	// 加载配置
	cfg, err := config.Load()
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	// 初始化日志
	if err := logger.Init(cfg.LogLevel, cfg.LogDir); err != nil {
		log.Fatalf("Failed to initialize logger: %v", err)
	}

	// 初始化数据库
	db, err := database.InitSQLite(cfg.DatabasePath)
	if err != nil {
		log.Fatalf("Failed to initialize database: %v", err)
	}

	// 初始化存储库
	userRepo := repository.NewUserRepository(db)

	// 初始化服务
	authService := service.NewAuthService(userRepo)
	userService := service.NewUserService(userRepo)

	// 设置Gin路由
	r := gin.Default()

	// 注册中间件
	r.Use(middleware.CORS())

	// 注册路由
	api.RegisterHomeRoutes(r)
	api.RegisterAuthRoutes(r, authService)
	api.RegisterUserRoutes(r, userService)

	// 添加 Swagger 路由
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	// 启动服务器
	logger.Info("Server is starting...")
	log.Printf("Server is running on :%s", cfg.Port)
	r.Run(":" + cfg.Port)
}
